#include <iostream>
#include <vector>

using std::cout;
using std::endl;
using std::vector;

template <typename Container>
void display(const Container &con)
{
    for(auto &elem : con)
    {
        cout << elem << "  ";
    }
    cout << endl;
}

void printCapacity(const vector<int> &vec)
{
    cout << "size() = " << vec.size() << endl;
    cout << "capacity() = " << vec.capacity() << endl;
}

void test()
{
    cout << "sizeof(vector<int>) = " << sizeof(vector<int>) << endl;
    cout << "sizeof(vector<long>) = " << sizeof(vector<long>) << endl;

    cout << endl;
    vector<int> number = {1, 3, 5, 7, 9, 4, 6, 8, 2};
    display(number);
    printCapacity(number);

    cout << endl << "在vector的尾部进行插入与删除" << endl;
    number.push_back(100);
    number.push_back(200);
    display(number);
    printCapacity(number);
    number.pop_back();
    display(number);
    printCapacity(number);

    //获取vector中的第一个元素的首地址？
    &number;//error,得不到第一个元素的首地址
    &*number.begin();//ok
    &number[0];//ok
    int *pdata = number.data();//ok

    cout << endl << "在vector的任意位置进行插入" << endl;
    vector<int>::iterator it = number.begin();
    it += 2;
    cout << "*it = " << *it << endl;
    number.insert(it, 300);
    display(number);
    cout << "*it = " << *it << endl;
    printCapacity(number);

    cout << endl;
    it = number.begin();
    it += 2;
    cout << "*it = " << *it << endl;
    number.insert(it, 5, 100);
    display(number);
    cout << "*it = " << *it << endl;
    printCapacity(number);

    //在vector中进行insert操作的时候，并不知道每次插入元素的个数，有可能在插入的
    //过程中底层因为没有足够的空间而发生扩容了,迭代器依旧指向的是老的空间,如果
    //后续还继续使用该迭代器进行操作，那么就会出现问题,这其实就是迭代器失效了
    //这种迭代器失效是因为底层发生了扩容导致的
    //解决问题：每次在使用迭代器之前，都重置迭代器位置
    cout << endl;
    vector<int> vec = {11, 33, 55, 88, 22};
    it = number.begin();
    it += 2;
    cout << "*it = " << *it << endl;
    number.insert(it, vec.begin(), vec.end());
    display(number);
    cout << "*it = " << *it << endl;
    printCapacity(number);

    cout << endl;
    it = number.begin();
    it += 2;
    cout << "*it = " << *it << endl;
    number.insert(it, {123, 567, 678, 345});
    display(number);
    cout << "*it = " << *it << endl;
    printCapacity(number);
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}

